import { mockData } from './data';
import axios from 'axios';

export const handleData = () => {
  const { correlation, varieties } = mockData;
  let obj = {} as any;
  const newData = correlation?.map((item) => {
    const [a, b, num] = item;
    let aName = varieties[Number(a)];
    let bName = varieties[Number(b)];

    if (Number(num) < 20) {
      if (obj[aName]) {
        obj[aName][bName] = num;
      } else {
        obj[aName] = {
          [bName]: num,
        };
      }
    }

    return [varieties[Number(a)], varieties[Number(b)], num];
  });

  // 输出每个aName在obj中的属性数量，并按数量从大到小排序
  const aNameCounts = Object.keys(obj).map((aName) => ({
    aName,
    count: Object.keys(obj[aName]).length,
  }));
  aNameCounts.sort((a, b) => b.count - a.count);
  console.log('aNameCounts', aNameCounts);
  aNameCounts.forEach(({ aName, count }) => {
    // console.log(`${aName} 属性数量:`, count);
  });

  console.log('obj', obj);
  console.log('newData', newData);

  return aNameCounts;
};

// 查询所有相关性分数都小于指定阈值的品种
export function getVarietiesByScoreRanges() {
  const { correlation, varieties } = mockData;
  const n = varieties.length;
  // 构建 n*n 的相关性矩阵
  const matrix = Array.from({ length: n }, () => Array(n).fill(null));
  correlation.forEach(([a, b, num]) => {
    const ai = Number(a);
    const bi = Number(b);
    if (num !== '-') {
      matrix[ai][bi] = Number(num);
    } else {
      matrix[ai][bi] = null;
    }
  });

  // 依次筛选所有相关性分数都小于等于0、10、20...100的品种
  const thresholds = Array.from({ length: 11 }, (_, i) => i * 10);
  const results: { threshold: number; added: string[]; all: string[] }[] = [];
  let prevSet = new Set<string>();
  thresholds.forEach((threshold, idx) => {
    const qualified: string[] = [];
    for (let i = 0; i < n; i++) {
      let allBelow = true;
      for (let j = 0; j < n; j++) {
        if (i === j) continue;
        const score = matrix[i][j];
        if (score === null) continue;
        if (score > threshold) {
          allBelow = false;
          break;
        }
      }
      if (allBelow) qualified.push(varieties[i]);
    }
    const currSet = new Set(qualified);
    const added = qualified.filter((x) => !prevSet.has(x));
    results.push({ threshold, added, all: qualified });
    prevSet = currSet;
  });
  return results;
}

// 请求远程相关性接口
export async function fetchVarietyCorrelation() {
  try {
    const params = new URLSearchParams();
    params.append('varieties', '所有');
    params.append('start', '2024-07-22');
    params.append('end', '2025-07-22');

    const response = await axios.post(
      'https://www.jiaoyikecha.com/ajax/variety_correlation.php?v=92c571cf',
      params,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );
    return response.data;
  } catch (error) {
    console.error('网络请求失败', error);
    throw error;
  }
}